//
//  FFPayPwdUpdateVC.m
//  LLWallet
//
//  Created by tt on 2020/9/1.
//

#import "FFPayPwdUpdateVC.h"
#import "FFPayPwdUpdateNextVC.h"
typedef enum : NSUInteger {
    CodeStatusNormal, // 正常
    CodeStatusGeting, // 获取中
    CodeStatusCountdown // 倒计时中
} CodeStatus;

static int lastGetCodeTimestamp = 0; // 最后一次获取验证码的时间戳（单位秒）

@interface FFPayPwdUpdateVC ()

@property(nonatomic,strong) UIImageView *bgImgView; // 背景图

@property(nonatomic,strong) UILabel *largeTitleLbl; // 大标题
@property(nonatomic,strong) UILabel *subTitleLbl; // 子标题

@property(nonatomic,strong) UILabel *zoneLbl; // 国家区号
@property(nonatomic,strong) UIView *zoneSplitLineView; // 区号分割线
@property(nonatomic,strong) UILabel *phoneLbl; // 当前用户手机号
@property(nonatomic,strong) UIView *lineView1; // 线1

@property(nonatomic,strong) UITextField *codeFd; // 验证码输入框
@property(nonatomic,strong) UIButton *getCodeBtn; // 获取验证码的Button
@property(nonatomic,strong) UIView *lineView2; // 线1

@property(nonatomic,strong) UIButton *nextBtn; // 下一步

@property(nonatomic,assign) CodeStatus status;
@property(nonatomic, strong) NSTimer *codeTimer;
@property(nonatomic) NSInteger countdownSec; //倒计时

@end

@implementation FFPayPwdUpdateVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.viewModel = [[FFPayPwdUpdateVM alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [self.view addSubview:self.bgImgView];
    [super viewDidLoad];
    
    [self.navigationBar setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:self.largeTitleLbl];
    [self.view addSubview:self.subTitleLbl];
    
    [self.view addSubview:self.zoneLbl];
    [self.view addSubview:self.zoneSplitLineView];
    [self.view addSubview:self.phoneLbl];
    [self.view addSubview:self.lineView1];
    
    [self.view addSubview:self.codeFd];
    [self.view addSubview:self.getCodeBtn];
    [self.view addSubview:self.lineView2];
    [self.view addSubview:self.nextBtn];
}



// ---------- 背景图片 ----------
- (UIImageView *)bgImgView {
    if(!_bgImgView) {
        _bgImgView = [[UIImageView alloc] initWithImage:[[WKApp shared] loadImage:@"bg" moduleID:@"LLWallet"]];
        _bgImgView.frame = self.view.bounds;
    }
    return _bgImgView;
}

- (UILabel *)largeTitleLbl {
    if(!_largeTitleLbl) {
        _largeTitleLbl = [[UILabel alloc] initWithFrame:CGRectMake(30.0f, 90.0f, 0.0f, 0.0f)];
        _largeTitleLbl.text = LLang(@"支付密码");
        [_largeTitleLbl setFont:[[WKApp shared].config appFontOfSizeSemibold:32.0f]];
        [_largeTitleLbl sizeToFit];
        
    }
    return _largeTitleLbl;
}
- (UILabel *)subTitleLbl {
    if(!_subTitleLbl) {
        _subTitleLbl = [[UILabel alloc] initWithFrame:CGRectMake(30.0f, self.largeTitleLbl.lim_bottom + 40.0f, 217.0f, 40.0f)];
        _subTitleLbl.text = [NSString stringWithFormat:LLang(@"%@会发送短信验证手机号码请输入您的验证码"),[WKApp shared].config.appName];
        _subTitleLbl.lineBreakMode = NSLineBreakByWordWrapping;
        _subTitleLbl.numberOfLines = 0.0f;
        [_subTitleLbl setFont:[[WKApp shared].config appFontOfSize:14.0f]];
        [_subTitleLbl setTextColor:[UIColor colorWithRed:192.0f/255.0f green:192.0f/255.0f blue:192.0f/255.0f alpha:1.0f]];
    }
    return _subTitleLbl;
}

- (UILabel *)zoneLbl {
    if(!_zoneLbl) {
        _zoneLbl = [[UILabel alloc] initWithFrame:CGRectMake(30.0f, self.subTitleLbl.lim_bottom+70.0f, 0.0f, 0.0)];
        NSString *zone =  [WKApp shared].loginInfo.extra[@"zone"];
        zone = [zone substringFromIndex:2];
        _zoneLbl.text =[NSString stringWithFormat:@"+ %@",zone];
        [_zoneLbl setFont:[[WKApp shared].config appFontOfSize:14.0f]];
        [_zoneLbl setTextColor:[WKApp shared].config.defaultTextColor];
        [_zoneLbl sizeToFit];
    }
    return _zoneLbl;
}

- (UIView *)zoneSplitLineView {
    if(!_zoneSplitLineView) {
        _zoneSplitLineView = [[UIView alloc] initWithFrame:CGRectMake(self.zoneLbl.lim_right+10.0f, self.zoneLbl.lim_top+4.0f, 1.0f, 10.0f)];
        [_zoneSplitLineView setBackgroundColor:[UIColor colorWithRed:216.0f/255.0f green:216.0f/255.0f blue:216.0f/255.0f alpha:1.0f]];
    }
    return _zoneSplitLineView;
}

- (UILabel *)phoneLbl {
    if(!_phoneLbl) {
        _phoneLbl = [[UILabel alloc] initWithFrame:CGRectMake(self.zoneSplitLineView.lim_right+10.0f, self.zoneLbl.lim_top-2.0f, 0.0f, 0.0f)];
        NSString *phone =  [WKApp shared].loginInfo.extra[@"phone"];
        if(phone.length == 11) {
            phone = [NSString stringWithFormat:@"%@ %@ %@",[phone substringWithRange:NSMakeRange(0, 3)],[phone substringWithRange:NSMakeRange(3, 4)],[phone substringFromIndex:7]];
        }
        _phoneLbl.text = phone;
        [_phoneLbl setFont:[[WKApp shared].config appFontOfSizeSemibold:16.0f]];
        [_phoneLbl sizeToFit];
    }
    return _phoneLbl;
}

- (UIView *)lineView1 {
    if(!_lineView1) {
        _lineView1 = [[UIView alloc] initWithFrame:CGRectMake(self.largeTitleLbl.lim_left, self.zoneLbl.lim_bottom+15.0f, self.view.lim_width-self.largeTitleLbl.lim_left*2, 1.0f)];
       _lineView1.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1.0];
    }
    return _lineView1;
}

- (UITextField *)codeFd {
    if(!_codeFd) {
        _codeFd = [[UITextField alloc] initWithFrame:CGRectMake(self.largeTitleLbl.lim_left, self.lineView1.lim_bottom+15.0f, 240.0f, 40.0f)];
        [_codeFd setPlaceholder:LLang(@"短信验证码")];
        _codeFd.keyboardType = UIKeyboardTypeNumberPad;
        _codeFd.returnKeyType = UIReturnKeyDone;
    }
    return _codeFd;
}

- (UIButton *)getCodeBtn {
    if(!_getCodeBtn) {
        _getCodeBtn = [[UIButton alloc] init];
        [_getCodeBtn setTitle:LLang(@"获取验证码") forState:UIControlStateNormal];
        [[_getCodeBtn titleLabel] setFont:[[WKApp shared].config appFontOfSizeSemibold:12.0f]];
        [_getCodeBtn setBackgroundColor:[WKApp shared].config.themeColor];
        _getCodeBtn.lim_width = 80.0f;
        _getCodeBtn.lim_height = 30.0f;
        _getCodeBtn.lim_top = self.codeFd.lim_top+5.0f;
        _getCodeBtn.lim_left = WKScreenWidth - _getCodeBtn.lim_width - 30.0f;
        _getCodeBtn.layer.masksToBounds = YES;
        _getCodeBtn.layer.cornerRadius = 4.0f;
        [_getCodeBtn addTarget:self action:@selector(sendCode) forControlEvents:UIControlEventTouchUpInside];
    }
    return _getCodeBtn;
}

- (UIView *)lineView2 {
    if(!_lineView2) {
        _lineView2 = [[UIView alloc] initWithFrame:CGRectMake(self.largeTitleLbl.lim_left, self.codeFd.lim_bottom+10.0f, self.lineView1.lim_width, 1.0f)];
        _lineView2.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1.0];
    }
    return _lineView2;
}

- (UIButton *)nextBtn {
    if(!_nextBtn) {
        _nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.largeTitleLbl.lim_left, self.lineView2.lim_bottom+50.0f, WKScreenWidth - self.largeTitleLbl.lim_left*2, 40.0f)];
        [_nextBtn setBackgroundColor:[WKApp shared].config.themeColor];
        [_nextBtn setTitle:LLang(@"下一步") forState:UIControlStateNormal];
        _nextBtn.layer.masksToBounds = YES;
        _nextBtn.layer.cornerRadius = 4.0f;
        [_nextBtn addTarget:self action:@selector(nextPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextBtn;
}

// 获取验证码
-(void) sendCode {
    int now = [[NSDate date] timeIntervalSince1970];
    if(now - lastGetCodeTimestamp< 60 ) {
        [self.view showHUDWithHide:[NSString stringWithFormat:LLang(@"发送验证码过于频繁，请在%d秒后重试"),(60 - (now-lastGetCodeTimestamp))]];
        return;
    }
    self.status = CodeStatusGeting;
    [self refreshSendCode];
    __weak typeof(self) weakSelf = self;
    [self.viewModel sendPayPwdUpdateCode].then(^(NSDictionary *resultDic){
        lastGetCodeTimestamp = [[NSDate date] timeIntervalSince1970];
        [weakSelf startCountDown]; // 开始倒计时
    }).catch(^(NSError *error){
        [weakSelf.view showHUDWithHide:error.domain];
        weakSelf.status = CodeStatusNormal;
        [weakSelf refreshSendCode];
    });

}

-(void) startCountDown {
    self.countdownSec = 60.0f; // 60秒倒计时
    self.status = CodeStatusCountdown;
    [self refreshSendCode];
    _codeTimer =
    [NSTimer scheduledTimerWithTimeInterval:1
                                     target:self
                                   selector:@selector(refreshSendCode)
                                   userInfo:nil
                                    repeats:YES];
}

-(void) refreshSendCode {
    if(self.status == CodeStatusNormal) {
        self.getCodeBtn.alpha = 1.0f;
        self.getCodeBtn.enabled = YES;
        [self.getCodeBtn setTitle:LLang(@"获取验证码") forState:UIControlStateNormal];
    }else if(self.status == CodeStatusGeting) {
        self.getCodeBtn.alpha = 0.5f;
        self.getCodeBtn.enabled = NO;
        [self.getCodeBtn setTitle:LLang(@"获取中") forState:UIControlStateNormal];
    }else if(self.status == CodeStatusCountdown) {
        if(self.countdownSec<=1) {
            [_codeTimer invalidate];
            _codeTimer = nil;
            self.status = CodeStatusNormal;
            [self refreshSendCode];
            return;
        }
        self.getCodeBtn.alpha = 0.5f;
        self.getCodeBtn.enabled = NO;
        [_getCodeBtn setTitle:[NSString stringWithFormat:LLang(@"重新发送(%li)"),(long)--self.countdownSec] forState:UIControlStateNormal];
        
    }
}

-(void) nextPressed {
    NSString *code = self.codeFd.text;
    if([code isEqualToString:@""]) {
        [self.view showHUDWithHide:LLang(@"验证码不能为空！")];
        return;
    }
    __weak typeof(self) weakSelf = self;
    
    FFPayPwdUpdateNextVC *vc = [FFPayPwdUpdateNextVC new];
       vc.type = PasswordTypeSetPayPwd;
       [vc setPasswordInputCompletion:^(NSString * _Nonnull password) {
           FFPayPwdUpdateNextVC *nextVC = [FFPayPwdUpdateNextVC new];
           nextVC.type = PasswordTypeComfirSetPayPwd;
           [nextVC setPasswordInputCompletion:^(NSString * _Nonnull repassword) {
               if(![password isEqualToString:repassword]) {
                   [weakSelf.view showMsg:LLangW(@"两次密码输入不一致！", weakSelf)];
                   return;
               }
               [[WKNavigationManager shared].topViewController.view showHUD];
               [weakSelf.viewModel setPayPwd:repassword code:code].then(^{
                   [[WKNavigationManager shared].topViewController.view hideHud];
                   [[WKNavigationManager shared] popToRootViewControllerAnimated:YES];
                   
               }).catch(^(NSError *error){
                   [[WKNavigationManager shared].topViewController.view switchHUDError:error.domain];
               });
               
           }];
           [[WKNavigationManager shared] pushViewController:nextVC animated:YES];
       }];
       [[WKNavigationManager shared] pushViewController:vc animated:YES];
   
//    [self.view showHUD];
//    [self.viewModel verityPayPwdUpdateCode:code].then(^{
//        [weakSelf.view hideHud];
//        FFPayPwdUpdateNextVC *vc = [FFPayPwdUpdateNextVC new];
//           vc.type = PasswordTypeSetPayPwd;
//           [vc setPasswordInputCompletion:^(NSString * _Nonnull password) {
//               FFPayPwdUpdateNextVC *nextVC = [FFPayPwdUpdateNextVC new];
//               nextVC.type = PasswordTypeComfirSetPayPwd;
//               [nextVC setPasswordInputCompletion:^(NSString * _Nonnull repassword) {
//                   if(![password isEqualToString:repassword]) {
//                       [weakSelf.view showMsg:LLangW(@"两次密码输入不一致！", weakSelf)];
//                       return;
//                   }
//                   [[WKNavigationManager shared].topViewController.view showHUD];
//                   [weakSelf.viewModel setPayPwd:repassword code:code].then(^{
//                       [[WKNavigationManager shared].topViewController.view hideHud];
//                       [[WKNavigationManager shared] popToRootViewControllerAnimated:YES];
//                       
//                   }).catch(^(NSError *error){
//                       [[WKNavigationManager shared].topViewController.view switchHUDError:error.domain];
//                   });
//                   
//               }];
//               [[WKNavigationManager shared] pushViewController:nextVC animated:YES];
//           }];
//           [[WKNavigationManager shared] pushViewController:vc animated:YES];
//    }).catch(^(NSError *error){
//        [weakSelf.view switchHUDError:error.domain];
//    });
}

- (void)dealloc {
    if(self.codeTimer) {
        [self.codeTimer invalidate];
        self.codeTimer = nil;
    }
}

@end
